﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SocketServer.ServerBase;
using SocketServer;
using LogLib;
using IUploading;

namespace SocketServer.ClientCommands
{
    public class Query : ClientRequestPackCommand<TransferDataPackge>
    {
        public IUpload Uploader = null;

        public string OutParams = "";

        public ClientRequestPackSession Session;

        public TransferServer Server = null;

        public override void ExecuteCommand(ClientRequestPackSession session, TransferDataPackge pack)
        {
            Session = session;
            Server = session.AppServer as TransferServer;
            Server.OnNewSessionRequestReceived(session, pack);
            if (!Server.Uploaders.ContainsKey(pack.InterfaceName))
            {
                Log.WriteAsync("不存在的接口:" + pack.InterfaceName);
                return;
            }
            Uploader = Server.Uploaders[pack.InterfaceName];
            if (Uploader == null)
            {
                Log.WriteAsync("接口对象为空:" + pack.InterfaceName);
                return;
            }
            string outstring = "";
            try
            {
                if (Uploader.Query(pack.InParams, out outstring))
                {
                    OnQueryOK(outstring);
                }
                else
                {
                    string reasonMsg = "Query失败:" + Uploader.ErrorMessage;
                    OnQueryFailed(reasonMsg, outstring);
                }
            }
            catch (Exception ex)
            {
                Server.OnCatchException(session, Uploader, TransferAction.Query, ex);
                return;
            }           
        }

        protected void OnQueryOK(string outParams)
        {
            TransferResponsePackge pack = new TransferResponsePackge(Uploader.InterfaceName, TransferAction.Query);
            pack.Result = TransferResult.QueryOK;
            pack.Success = true;           
            pack.Message = "";          
            pack.SetParams(outParams);
            if (Session.Connected)
            {
                Session.Send(pack);
            }    
            Server.ReportTransferReponse(pack);
        }

        protected void OnQueryFailed(string reasonMsg, string outParams)
        {
            TransferResponsePackge pack = new TransferResponsePackge(Uploader.InterfaceName, TransferAction.Query);
            pack.Result = TransferResult.QueryFailed;
            pack.Success = true;
            pack.Message = reasonMsg;
            pack.SetParams(outParams);
            if (Session.Connected)
            {
                Session.Send(pack);
            }    
            Server.ReportTransferReponse(pack);
        }
    }
}
